<template>
  <a-card title="权限查询" :bordered="false" class="condition-card">
    <div class="condition-row">
      <div class="condition-col flex align-center justify-between">
        <a-input allow-clear placeholder="请输入权限名称" v-model:value="conditionState.menuName"></a-input>
        <a-button class="ml-12" type="primary" :loading="searchLoading" @click="handleSearch">查询</a-button>
      </div>
    </div>
  </a-card>
  <a-card title="权限列表" :bordered="false" class="result-card mt-20">
    <template #extra>
      <a-button type="primary" class="mr-20" :loading="initLoading" v-if="needInitDef" @click="handleInitDefMenuAuth">初始化权限</a-button>
      <a-button type="primary" @click="handlePopCreateModal">添加权限</a-button>
    </template>
    <a-table :columns="columns" :data-source="menuList" :pagination="false" :scroll="{y: 'calc(100vh - 405px)'}">
      <template #bodyCell="{record, column}">
        <template v-if="column.dataIndex === 'option'">
          <a-button type="link" @click="handlePopEditModal(record)">
            <i class="iconfont icon-bianji"></i>
          </a-button>
          <a-popconfirm
              v-if="!defAuthObj[record.menuCode]"
              title="确定要删除吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelRecord(record)">
            <a-button type="link" class="ml-12" danger>
              <i class="iconfont icon-shanchu"></i>
            </a-button>
          </a-popconfirm>

        </template>
      </template>
    </a-table>
    <div class="pagination-content flex justify-end">
      <a-pagination v-model:current="conditionState.page" show-quick-jumper show-size-changer :show-total="total => `共 ${total} 条`" :total="total" v-model:pageSize="conditionState.size" @change="handlePageChange" />
    </div>
  </a-card>
  <a-modal :width="520" :title="editMode ? '编辑权限信息' : '添加权限信息'" v-model:visible="modalVisible" :confirmLoading="saveLoading" @ok="handleSave">
    <a-form
        layout="vertical"
        :model="formState"
        :rules="rules"
        ref="formRef">
      <a-form-item
          label="权限名称"
          name="menuName">
        <a-input v-model:value="formState.menuName" placeholder="请输入权限名称"></a-input>
      </a-form-item>
      <a-form-item
          label="权限编码"
          name="menuCode">
        <a-input :disabled="editMode" v-model:value="formState.menuCode" placeholder="请输入权限编码"></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {nextTick, reactive, ref} from "vue";
import api from '../../api/menus'
import authApi from '../../api/auth'
import {RoleItem, MenuItem, ResDto, RoleMenuItem} from '../../types/common'
import {DefAuthList} from '../../common/constants'
import {uuid} from '../../common/utils'
import {message} from "ant-design-vue";
const defAuthObj = ref({})
DefAuthList.forEach((item: any) => {
  defAuthObj.value[item.menuCode] = item
})
const modalVisible = ref<boolean>(false)
const editMode = ref<boolean>(false)
const defFormState = {
  menuName: '',
  menuCode: ''
}
const currentFormItem = ref({})
const formState = ref({...defFormState})
const formRef = ref()
const rules = {
  menuName: [
    { required: true, trigger: 'blur', message: '请输入权限名称' },
  ],
}
const searchLoading = ref<boolean>(false)
const saveLoading = ref<boolean>(false)
const conditionState = reactive({
  menuName: '',
  page: 1,
  size: 10,
})
const total = ref<number>(0)
const menuList = ref<MenuItem[]>([])
const columns = [
  {
    dataIndex: 'menuName',
    key: 'menuName',
    title: '权限名称',
  },{
    dataIndex: 'menuCode',
    key: 'menuCode',
    title: '权限编码',
  },{
    dataIndex: 'option',
    key: 'option',
    title: '操作',
  },
]
const needInitDef = ref(false)
const getPageData = async () => {
  searchLoading.value = true
  menuList.value = []
  try {
    const res = await api.getList({
      menuName: conditionState.menuName || '',
      page: conditionState.page - 1,
      size: conditionState.size,
    })
    searchLoading.value = false
    if (res.content) {
      total.value = res.content.total || 0
      if (res.content.content && res.content.content.length) {
        menuList.value = res.content.content
      }
      if (total.value === 0) {
        needInitDef.value = true
      }
    }
  } catch(e: any) {
    searchLoading.value = false
  }

}

const handleSearch = () => {
  conditionState.page = 1
  total.value = 0
  getPageData()
}
const handlePageChange = (page: number, pageSize: number) => {
  if (pageSize !== conditionState.size) {
    conditionState.page = 1
  }
  getPageData()
}
handleSearch()
const handleSave = async () => {
  try {
    await formRef.value.validateFields()
    console.log('formState', formState.value)
    saveLoading.value = true
    let res
    if (!editMode.value) {
      res = await api.create(formState.value)
    } else {
      res = await api.edit(formState.value)
    }
    saveLoading.value = false
    if (res.success) {
      if (!editMode.value) {
        message.success('权限添加成功')
        handleSearch()
      } else {
        message.success('权限修改成功')
        Object.assign(currentFormItem.value, formState.value)
      }
      modalVisible.value = false
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  }catch(e){
    saveLoading.value = false
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}
const handlePopCreateModal = () => {
  formState.value = {...defFormState}
  formState.value.menuCode = uuid(8, 0, '0123456789')
  editMode.value = false;
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const handlePopEditModal = (item: any) => {
  currentFormItem.value = item
  Object.assign(formState.value, item)
  editMode.value = true;
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const handleDelRecord = async (item: MenuItem) => {
  try {
    const res = await api.del(item.menuCode)
    if (res.success) {
      message.success('权限删除成功')
      handleSearch()
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  }catch(e){
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}
const initLoading = ref(false)
const handleInitDefMenuAuth = async () => {
  initLoading.value = true
  const size = DefAuthList.length
  for(let i=0; i<size; i++) {
    await api.create({
      menuCode: DefAuthList[i].menuCode,
      menuName: DefAuthList[i].menuName,
    })
  }
  initLoading.value = false
  needInitDef.value = false
}
</script>

<style scoped lang="less">
.condition-col{
  .ant-input{
    min-width: 300px;
  }
  .ant-select{
    min-width: 160px;
  }
}
.ant-btn-link{
  padding: 0;
}
</style>
